import { useEffect, useRef, useState } from "react";
import { PageContainer } from "@ant-design/pro-layout";
import { fetchList as fetchStudentList } from "@/api/student";
import { fetchList as fetchClassRecordList } from "@/api/studentClassRecord";

import { Row, Col, List, Card, Statistic, Typography } from "antd";
import moment from "moment";

export default () => {
  const actionRef = useRef();
  const formRef = useRef();
  const [studentList, setStudentList] = useState([]);
  const [currentMonthObj, setCurrentMonthObj] = useState({
    currentMonthClassHour: 0, // 本月消耗课时
    currentMonthClassHour_li: 0, // 本月李老师消耗课时
    lastMonthClassHour: 0, // 上月消耗课时
    lastMonthClassHour_li: 0, // 上月李老师消耗课时
    currentWeekClassHour: 0, // 本周消耗课时
  });

  const getStudentList = async () => {
    const res = await fetchStudentList({
      page: 1,
      pageSize: 500,
    });
    setStudentList(res.data);
  };

  const getClassRecordList = async () => {
    const res = await fetchClassRecordList({
      page: 1,
      pageSize: 1000,
    });
    // 本月正则
    const currentMonthPattern = new RegExp(
      `^${moment().format("YYYY/MM")}/\\d{2}`
    );
    // 上月正则
    const lastMonthPattern = new RegExp(
      `^${moment().subtract(1, "month").format("YYYY/MM")}/\\d{2}`
    );

    // 筛选出本月且已扣款的记录
    const currentMonthList = res.data.filter(
      (item) => currentMonthPattern.test(item.classDateStr) && item.isDeduct
    );

    const lastMonthList = res.data.filter(
      (item) => lastMonthPattern.test(item.classDateStr) && item.isDeduct
    );

    // 获取本周的开始和结束
    const startOfWeek = moment().startOf("week"); // 本周一
    const endOfWeek = moment().endOf("week"); // 本周日
    // 生成本周的所有日期字符串数组
    const weekDays = [];
    let current = startOfWeek.clone();
    while (current <= endOfWeek) {
      weekDays.push(current.format("YYYY/MM/DD"));
      current = current.add(1, "day");
    }

    // 本周正则表达式字符串
    const pattern_week = new RegExp("^(" + weekDays.join("|") + ")");

    setCurrentMonthObj({
      // 本月消耗课时
      currentMonthClassHour: currentMonthList?.reduce(
        (a, b) => a + b.lessonConsumption,
        0
      ),
      // 本月李老师消耗课时
      currentMonthClassHour_li: currentMonthList
        ?.filter((item) => item.teacherId == "67a5c253532d9076ea0b340f")
        ?.reduce((a, b) => a + b.lessonConsumption, 0),
      // 上月消耗课时
      lastMonthClassHour: lastMonthList?.reduce(
        (a, b) => a + b.lessonConsumption,
        0
      ),
      // 上月李老师消耗课时
      lastMonthClassHour_li: lastMonthList
        ?.filter((item) => item.teacherId == "67a5c253532d9076ea0b340f")
        ?.reduce((a, b) => a + b.lessonConsumption, 0),
      // 本周消耗课时
      currentWeekClassHour: currentMonthList
        .filter((item) => pattern_week.test(item.classDateStr))
        ?.reduce((a, b) => a + b.lessonConsumption, 0),
    });
  };

  useEffect(() => {
    getStudentList();
    getClassRecordList();
  }, []);

  return (
    <PageContainer>
      <Row gutter={24}>
        <Col span={8}>
          <Card>
            <Statistic
              title="在读学员"
              value={studentList.filter((item) => item.status == 1)?.length}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="停课学员"
              value={studentList.filter((item) => item.status == 2)?.length}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="未读学员"
              value={studentList.filter((item) => item.status == 3)?.length}
            />
          </Card>
        </Col>
      </Row>
      <Row gutter={24} style={{ marginTop: 24 }}>
        <Col span={8}>
          <Card>
            <Statistic
              title="校区收入（2025年开始）"
              prefix="￥"
              value={studentList?.reduce((a, b) => a + b.amountMoney, 0)}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="未消课时"
              valueStyle={{ color: "red", fontWeight: "bold" }}
              value={studentList
                ?.filter((item) => item.status == 1 || item.status == 2)
                ?.reduce((a, b) => a + b.classHour, 0)}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="本周消课时"
              value={currentMonthObj.currentWeekClassHour}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={24} style={{ marginTop: 24 }}>
        <Col span={8}>
          <Card>
            <List
              header={
                <Statistic
                  title="预警学员（小于20课时）"
                  value={
                    studentList?.filter(
                      (item) => item.status == 1 && item.classHour <= 20
                    ).length
                  }
                />
              }
              dataSource={studentList?.filter(
                (item) => item.status == 1 && item.classHour <= 20
              )}
              renderItem={(item) => (
                <List.Item>
                  <div
                    style={{
                      width: "100%",
                      display: "flex",
                      justifyContent: "space-between",
                    }}
                  >
                    <Typography.Text type="danger">
                      [{item.name}]
                    </Typography.Text>
                    <span> 剩余课时：{item.classHour}</span>
                  </div>
                </List.Item>
              )}
            />
          </Card>
        </Col>
        <Col span={16}>
          <Row gutter={24}>
            <Col span={12}>
              <Card>
                <Statistic
                  title="上月消课时"
                  value={currentMonthObj.lastMonthClassHour}
                />
              </Card>
            </Col>
            <Col span={12}>
              <Card>
                <Statistic
                  title="上月李老师消课时"
                  value={currentMonthObj.lastMonthClassHour_li}
                />
              </Card>
            </Col>
          </Row>
          <Row gutter={24} style={{ marginTop: 24 }}>
            <Col span={12}>
              <Card>
                <Statistic
                  title="本月消课时"
                  value={currentMonthObj.currentMonthClassHour}
                />
              </Card>
            </Col>
            <Col span={12}>
              <Card>
                <Statistic
                  title="本月李老师消课时"
                  value={currentMonthObj.currentMonthClassHour_li}
                />
              </Card>
            </Col>
          </Row>
        </Col>
      </Row>
    </PageContainer>
  );
};
